package com.zbkj.crmeb.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.store.dao.EmployeeFileDao;
import com.zbkj.crmeb.store.service.EmployeeFileService;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.model.SystemRole;
import com.zbkj.crmeb.system.request.SystemAdminAddRequest;
import com.zbkj.crmeb.system.request.SystemAdminRequest;
import com.zbkj.crmeb.system.response.SystemAdminResponse;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.system.service.SystemRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class EmployeeFileServiceImpl extends ServiceImpl<EmployeeFileDao, SystemAdmin> implements EmployeeFileService {
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private SystemRoleService systemRoleService;

    /**
     * 功能描述: 新增员工账号
     * @Param: [systemAdminAddRequest]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/11/24 16:05
     */
    @Override
    public Boolean saveEmployeeAccount(SystemAdminAddRequest systemAdminAddRequest) throws Exception {
        //子账号数量
        int count = systemAdminService.count(Wrappers.<SystemAdmin>lambdaQuery()
                .eq(SystemAdmin::getMerId, systemAdminAddRequest.getMerId())
                .eq(SystemAdmin::getIdentityType, 2)) - 1;

        ChannelMerchant one = channelMerchantService.getOne(Wrappers.<ChannelMerchant>lambdaQuery()
                .eq(ChannelMerchant::getId, systemAdminAddRequest.getMerId().substring(1, systemAdminAddRequest.getMerId().length() - 1))
                .last("limit 1"));
        //子账号数量大于或等于设置的子账号数量
        if (count >= one.getSubAccountNumber()){
            throw new CrmebException("当前人数已达上限，请及时联系客服");
        }

        systemAdminService.validatedSystemAdmin(systemAdminAddRequest);
        return Objects.nonNull(systemAdminService.saveAdmin(systemAdminAddRequest));
    }

    /**
     * 功能描述: 修改员工账号
     * @Param: [systemAdminRequest]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/11/24 16:09
     */
    @Override
    public Boolean updateEmployeeAccount(SystemAdminRequest systemAdminRequest) throws Exception {
        systemAdminService.validatedSystemAdmin(systemAdminRequest);
        return Objects.nonNull(systemAdminService.updateAdmin(systemAdminRequest, null));
    }

    /**
     * 功能描述: 分页查询员工档案信息/根据工号、姓名、角色模糊查询员工
     * @Param: [request, pageParamRequest]
     * @Return: com.github.pagehelper.PageInfo<com.zbkj.crmeb.system.response.SystemAdminResponse>
     * @Author: wangzh
     * @Date: 2022/11/24 18:06
     */
    @Override
    public PageInfo<SystemAdminResponse> getEmployeeAccountByCode(SystemAdminRequest request, PageParamRequest pageParamRequest) {
        List<SystemAdminResponse> responses = new ArrayList<>();
        String primaryAccountName = getPrimaryAccountName(request.getMerId());
        LambdaQueryWrapper<SystemAdmin> queryWrapper = new LambdaQueryWrapper<>();
        //查询当前商户下，身份类型为商家，并且排除主账号
        queryWrapper.eq(SystemAdmin::getMerId, request.getMerId())
                .eq(SystemAdmin::getIdentityType, 2)
                .ne(SystemAdmin::getAccount, primaryAccountName);
        //工号模糊查询
        if (StringUtils.isNotBlank(request.getEmployeeCode())){
            queryWrapper.like(SystemAdmin::getEmployeeCode, request.getEmployeeCode());
        }

        //姓名模糊查询
        if (StringUtils.isNotBlank(request.getRealName())){
            queryWrapper.like(SystemAdmin::getRealName, request.getRealName());
        }

        //角色
        if (StringUtils.isNotBlank(request.getRoles())){
            queryWrapper.eq(SystemAdmin::getRoles, request.getRoles());
        }
        //查询员工数据
        Page<Object> pageInfo = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<SystemAdmin> systemAdminList = systemAdminService.list(queryWrapper);
        if (CollectionUtils.isEmpty(systemAdminList)){
            return CommonPage.copyPageInfo(pageInfo, new ArrayList<>());
        }

        Set<Integer> roleIdSet = new HashSet<>();
        systemAdminList.stream().map(SystemAdmin::getRoles).map(e -> e.split(",")).forEach(s -> {
            for (String id : s){
                roleIdSet.add(Integer.valueOf(id));
            }
        });
        List<Integer> roleIds = new ArrayList<>(roleIdSet);

        //角色列表
        List<SystemRole> roleList = systemRoleService.getListInIds(roleIds);

        //角色id对应名字
        Map<Integer, String> roleNameMap = roleList.stream().collect(Collectors.toMap(SystemRole::getId, SystemRole::getRoleName));
        for (SystemAdmin systemAdmin : systemAdminList){
            SystemAdminResponse systemAdminResponse = new SystemAdminResponse();
            BeanUtils.copyProperties(systemAdmin, systemAdminResponse);
            StringBuilder stringBuilder = new StringBuilder();
            for (String id : systemAdmin.getRoles().split(",")){
                stringBuilder.append(roleNameMap.get(Integer.valueOf(id)));
                stringBuilder.append(",");
            }
            systemAdminResponse.setRoleNames(stringBuilder.substring(0, stringBuilder.length() - 1));
            responses.add(systemAdminResponse);
        }

        return CommonPage.copyPageInfo(pageInfo, responses);
    }

    /**
     * 功能描述: 获取主账号名称
     * @Param: [merId]
     * @Return: java.lang.String
     * @Author: wangzh
     * @Date: 2022/11/25 9:26
     */
    @Override
    public String getPrimaryAccountName(String merId) {
        SystemAdmin one = systemAdminService.getOne(Wrappers.<SystemAdmin>lambdaQuery()
                .eq(SystemAdmin::getMerId, merId)
                .eq(SystemAdmin::getIdentityType, 2)
                .orderByAsc(SystemAdmin::getId)
                .last("limit 1"));
        return one.getAccount();
    }

    /**
     * 功能描述: 根据id删除账号
     * @Param: [id]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/11/25 10:19
     */
    @Override
    public Boolean deleteEmployAccount(Integer id) {
        return systemAdminService.removeById(id);
    }

    /**
     * 功能描述: 根据id获取账号信息
     * @Param: [id]
     * @Return: com.zbkj.crmeb.system.response.SystemAdminResponse
     * @Author: wangzh
     * @Date: 2022/11/29 10:09
     */
    @Override
    public SystemAdminResponse getEmployAccountById(Integer id) throws Exception {
        SystemAdminRequest request = new SystemAdminRequest();
        request.setId(id);
        SystemAdminResponse systemAdminInfo = systemAdminService.getInfo(request);
        List<Integer> ids = Arrays.stream(systemAdminInfo.getRoles().split(",")).map(Integer::valueOf).collect(Collectors.toList());
        List<SystemRole> systemRoleList = systemRoleService.getListInIds(ids);
        String roleNames = systemRoleList.stream().map(SystemRole::getRoleName).collect(Collectors.joining(","));
        systemAdminInfo.setRoleNames(roleNames);
        return systemAdminInfo;
    }

}
